package com.healthtop.service.impl;

import com.healthtop.dao.XsRoleResourceDao;
import com.healthtop.dto.XsRoleResourceDto;
import com.healthtop.model.XsRoleResource;
import com.healthtop.service.XsRoleResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class XsRoleResourceServiceImpl implements XsRoleResourceService {

    @Autowired
    private XsRoleResourceDao roleResourceDao;

    @Override
    public void save(XsRoleResource roleResource) {
        roleResourceDao.save(roleResource);
    }

    @Override
    public List<XsRoleResource> selectByRoleId(Long roleId) {
        return roleResourceDao.selectByRoleId(roleId);
    }

    @Override
    public List<XsRoleResource> selectByResourceId(Long resourceId) {
        return roleResourceDao.selectByResourceId(resourceId);
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        roleResourceDao.deleteByRoleId(roleId);
    }

    @Override
    public void deleteByResourceId(Long resourceId) {
        roleResourceDao.deleteByResourceId(resourceId);
    }

    @Override
    public void submitRoleResource(XsRoleResourceDto roleResourceDto) {
        if(roleResourceDto.getRid()!=0) {
            roleResourceDao.deleteByRoleId(roleResourceDto.getRid());
            if (!StringUtils.isEmpty(roleResourceDto.getResourceIds())) {
                String[] resourceIds = roleResourceDto.getResourceIds().split(",");
                for (int i = 0; i < resourceIds.length; i++) {
                    XsRoleResource roleResource = new XsRoleResource();
                    roleResource.setResourceId(Long.parseLong(resourceIds[i]));
                    roleResource.setRid(roleResourceDto.getRid());
                    roleResourceDao.save(roleResource);
                }
            }
        }
    }

}
